package oneroom.comm;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {

	private static final long serialVersionUID = 4524091036023098210L;
	private static String baseDir = "/download/";
	
	private File getFile(String directory, String filename) throws UnsupportedEncodingException{
		File file = new File(directory, filename);
		if (!file.exists()) {
			file = new File(directory, URLDecoder.decode(filename, "UTF-8"));
			if (!file.exists()) {
				file = new File(directory, URLDecoder.decode(filename, "CP949"));
			}
		}
		return file; 
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String name = req.getParameter("name");
		String kind = req.getParameter("kind");
		String directory = commPath.UPLOAD_PATH;
		if(kind == null || kind.equals("")){
			directory = commPath.UPLOAD_PATH;
		}else if(kind.equals("img")){
			directory = commPath.UPLOAD_PATH;
		}else if(kind.equals("qr")){
			directory = commPath.UPLOAD_PATH;
		}
		
		int idx = req.getRequestURI().indexOf(baseDir) + baseDir.length();
		String filename = req.getRequestURI().substring(idx);
		if(!kind.equals("img")){
			if (filename.indexOf("..") != -1) {
				resp.sendError(403);
				return;
			}
			if (filename.length() == 0 || filename.lastIndexOf('/') == filename.length()-1) {
				resp.sendError(404);
				return;
			}
		}else{
			if(filename != null && !filename.equals("")){
				filename = name;
			}else{
				filename = "noimg.jpg";
			}
		}
		File file= getFile(directory, filename);
		if (file.exists()) {
			resp.reset();
			if (name == null) {
				name = file.getName();
			}
			
			if (req.getHeader("User-Agent").toLowerCase().indexOf("firefox") != -1) {
				resp.setHeader("Content-Type", "application/download");
				resp.setHeader("Content-Length", ""+file.length());
				resp.setHeader("Content-Disposition", "attachment; filename=\"" + new String(name.getBytes("UTF-8"), "ISO-8859-1") + "\"");
			} else {
				//resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(name,"UTF-8"));
				resp.setHeader("Pragma", "public");
				resp.setHeader("Expires", "0");
				resp.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
				resp.setHeader("Content-Type", "application-download");
				resp.setHeader("Content-Length", ""+file.length());
				resp.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(name,"UTF-8") + "\";");
				resp.setHeader("Content-Transfer-Encoding", "binary");

			}
			
			BufferedInputStream fin = new BufferedInputStream(new FileInputStream(file));
			BufferedOutputStream outs = new BufferedOutputStream(resp.getOutputStream());
			int leng = 0;
			byte b[] = new byte[4096];
			while( (leng = fin.read(b, 0, 4096)) != -1 ){
				outs.write(b,0,leng);
			}
			outs.flush();
	   		outs.close();
	   		fin.close();
		} else {
			resp.sendError(404);
		}
	}

}
